/**
 * 主题工具钩子
 * 处理主题切换、检测系统主题及同步
 * @author LYC
 * @date 2025-09-14
 */

import { useUIStore } from '@/store/ui'
import { watch, onBeforeUnmount } from 'vue'

export function useThemeTool(): {
  listenToSystemTheme: () => void
  setThemeSource: (source: 'system' | 'light' | 'dark') => Promise<void>
  applyTheme: () => void
  initTheme: () => void
} {
  const uiStore = useUIStore()
  const ipcRenderer = window.electron?.ipcRenderer

  // 系统主题监听
  const listenToSystemTheme = (): void => {
    if (ipcRenderer) {
      // 监听系统主题变化
      ipcRenderer.on('system-theme-changed', (_, theme) => {
        if (uiStore.themeSource === 'system') {
          uiStore.setTheme(theme)
        }
      })

      // 初始获取系统主题
      ipcRenderer
        .invoke('get-system-theme')
        .then((theme) => {
          if (uiStore.themeSource === 'system') {
            uiStore.setTheme(theme)
          }
        })
        .catch((err) => {
          console.error('获取系统主题失败:', err)
        })

      // 保存监听器引用以便后续移除
      const systemThemeListener = (_, theme): void => {
        if (uiStore.themeSource === 'system') {
          uiStore.setTheme(theme)
        }
      }

      // 添加监听器
      ipcRenderer.on('system-theme-changed', systemThemeListener)

      // 组件卸载时移除监听器
      onBeforeUnmount(() => {
        ipcRenderer.removeListener('system-theme-changed', systemThemeListener)
        console.log('移除系统主题变化监听器')
      })
    } else {
      // Web环境使用媒体查询
      const darkModeMediaQuery = window.matchMedia('(prefers-color-scheme: dark)')

      const handleSystemThemeChange = (e: MediaQueryListEvent): void => {
        if (uiStore.themeSource === 'system') {
          uiStore.setTheme(e.matches ? 'dark' : 'light')
        }
      }

      // 初始设置
      if (uiStore.themeSource === 'system') {
        uiStore.setTheme(darkModeMediaQuery.matches ? 'dark' : 'light')
      }

      // 监听系统主题变化
      darkModeMediaQuery.addEventListener('change', handleSystemThemeChange)

      // 组件卸载时移除监听器
      onBeforeUnmount(() => {
        darkModeMediaQuery.removeEventListener('change', handleSystemThemeChange)
      })
    }
  }

  // 设置主题源
  const setThemeSource = async (source: 'system' | 'light' | 'dark'): Promise<void> => {
    uiStore.themeSource = source

    if (source === 'system') {
      // 如果设置为跟随系统，则获取当前系统主题
      if (ipcRenderer) {
        const systemTheme = await ipcRenderer.invoke('get-system-theme')
        uiStore.setTheme(systemTheme)

        // 同步到主进程
        ipcRenderer.invoke('set-theme-source', 'system')
      } else {
        // Web环境
        const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches
        uiStore.setTheme(isDarkMode ? 'dark' : 'light')
      }
    } else {
      // 手动设置主题
      uiStore.setTheme(source)

      // 同步到主进程
      if (ipcRenderer) {
        ipcRenderer.invoke('set-theme-source', source)
      }
    }

    // 保存到本地存储
    localStorage.setItem('theme-source', source)
    localStorage.setItem('theme', uiStore.theme)

    // 应用主题
    applyTheme()
  }

  // 应用主题到DOM
  const applyTheme = (): void => {
    document.documentElement.setAttribute('data-theme', uiStore.theme)
  }

  // 初始化主题
  const initTheme = (): void => {
    // 从本地存储读取主题配置
    const savedThemeSource =
      (localStorage.getItem('theme-source') as 'system' | 'light' | 'dark') || 'system'
    const savedTheme = localStorage.getItem('theme') as 'light' | 'dark'

    // 设置初始状态
    uiStore.themeSource = savedThemeSource || 'system'

    if (savedThemeSource === 'system') {
      // 如果是跟随系统，开始监听
      listenToSystemTheme()
    } else if (savedTheme) {
      // 如果有保存的主题，直接应用
      uiStore.setTheme(savedTheme)
    }

    // 监听主题变化并应用
    watch(
      () => uiStore.theme,
      () => {
        applyTheme()
      },
      { immediate: true }
    )
  }

  return {
    listenToSystemTheme,
    setThemeSource,
    applyTheme,
    initTheme
  }
}
